package com.lsq.baseadmin.common.component;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lsq.baseadmin.common.constant.ConstantSystem;
import com.lsq.baseadmin.common.enums.DataScopeEnum;
import com.lsq.baseadmin.modules.manage.entity.User;
import com.lsq.baseadmin.modules.manage.entity.UserDataScope;
import com.lsq.baseadmin.modules.manage.vo.UserVo;
import com.lsq.baseadmin.modules.manage.utils.AuthUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * 数据权限
 *
 * @author lsq
 * @since 2020/11/9 10:30
 */
@Component
public class DataScope {

    /**
     * 做数据权限的表一定要有 ConstantSystem.FIELD_OWNER,ConstantSystem.FIELD_DEPARTMENT 所配置的字段
     * @param wrapper 查询条件
     */
    public void setDataScope (QueryWrapper<?> wrapper) {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();

        UserVo loginUser = AuthUtil.getLoginUser(request.getSession());
        User user = loginUser.getUser();
        int dataScope = user.getDataScope();

        // 全部不做限制
        if (DataScopeEnum.ALL.getValue().equals(dataScope)) {
            return;
        }
        // 个人
        if (DataScopeEnum.SELF.getValue().equals(dataScope)) {
            wrapper.eq(ConstantSystem.FIELD_OWNER, user.getId());
            return;
        }
        // 本部门
        if (DataScopeEnum.DEPARTMENT.getValue().equals(dataScope)) {
            wrapper.eq(ConstantSystem.FIELD_DEPARTMENT, user.getDepartmentId());
            return;
        }
        // 本部门及子部门
        if (DataScopeEnum.DEPARTMENT_AND_SUB_DEPARTMENT.getValue().equals(dataScope)) {
            userDataScopesToString(wrapper, loginUser.getUserDataScopes());
            return;
        }
        // 自定义
        if (DataScopeEnum.CUSTOMIZED.getValue().equals(dataScope)) {
            userDataScopesToString(wrapper, loginUser.getUserDataScopes());
        }
    }

    private void userDataScopesToString (QueryWrapper<?> wrapper, List<UserDataScope> list) {
        if (list == null || list.size() < 1) {
            return;
        }
        List<Integer> ids = new ArrayList<>();
        list.forEach(o -> ids.add(o.getDepartmentId()));
        wrapper.in(ConstantSystem.FIELD_DEPARTMENT, ids);
    }

}
